// 导航守卫
// 1.导入路由模块
import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// console.log(store)

// 2.为路由对象，挂载导航守卫
// bdforeEach 是全局前置守卫
router.beforeEach((to, from, next) => {
  // 只要发生路由导航跳转，就要Mprogress.start(展示进度条)
  // 获取token，判断用户访问是否有权限页面
  NProgress.start()
  const token = store.getters.token
  if (to.path === '/login' || to.path === '/404') {
    if (to.path === '/login' && token) {
      next('/')
      NProgress.done()
    } else {
      next()
    }
  } else {
    if (token) {
      store.dispatch('user/initUserInfo')
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// afterEach 是全局后置导航守卫，只有两个参数
router.afterEach((to, from) => {
  NProgress.done()
})
